<?php
exists_frame();
//调度器
final class __X_APP__ {
    protected $app_instance;
    protected $app_method;
    protected $cfg;
    public function __construct() {
        $this->define_env_constanst();
        $this->load_cfg();
        $this->set_time_zone();
        $this->load_application_class_file();
        //$this->uri_analyze();
    }
    private function define_env_constanst() {
        $in_root = dirname($_SERVER['PHP_SELF']) == '/' ;
        if($in_root) {
            define('__X_WEB_ROOT__',dirname($_SERVER['SCRIPT_FILENAME']));
        } else {
            define('__X_WEB_ROOT__',str_replace($_SERVER['PHP_SELF'],'',$_SERVER['SCRIPT_FILENAME']));
        }
        define('__X_APP_ROOT__',$this->findappdir(__X_WEB_ROOT__));
        define('__X_APP_DIRECTORY_NAME__', $this->findappname(__X_WEB_ROOT__));
        define('__X_CALL_PAGE_NAME__',basename($_SERVER['SCRIPT_FILENAME'],'.php'));
        define('__X_CALL_PAGE_DIR__',dirname($_SERVER['SCRIPT_FILENAME']));
    }
    private function findappname($dir, $up ='') {
        $suffix = basename($dir);
        if(empty($suffix)) return '';
        if(strtolower($suffix) == 'www') {
            return $up;
        }
        $dir = dirname($dir);
        return $this->findappname($dir,$suffix);
    }
    private function findappdir($dir) {
        $suffix = basename($dir);
        if(empty($suffix)) return '';
        if(strtolower($suffix) == 'www') {
            return dirname($dir);
        }
        return $this->findappdir(dirname($dir));
    }
    public function load_application_class_file() {
        include_once(__X_CALL_PAGE_DIR__. '/index.php');
        if(strtolower(__X_CALL_PAGE_NAME__) != 'index') {
            $function = __X_CALL_PAGE_NAME__;
            include_once($_SERVER['SCRIPT_FILENAME']);
        } else {
            $function = 'defaults';
        }
        $this->app_instance = new index($this->cfg);
        $this->app_instance->run($function);
    }
    public function load_cfg() {
        include_once(FRAMEWORK_ROOT . '/config.default.php');
        if(file_exists(APP_ROOT. '/data/config.php')) {
            include_once(APP_ROOT . '/data/config.php');
        }
        $this->cfg = &$cfg;
    }
    public function set_time_zone() {
        if(empty($this->cfg['timezone'])) {
            if(SHOW_DEBUG) throw new debug('Application timezone unset in config file ');
            include_once(FRAMEWORK_ROOT . '/config.default.php');
            date_default_timezone_set($cfg['timezone']);
            return;
        }
        date_default_timezone_set($this->cfg['timezone']);
    }
    public function __destruct() {
        $this->app_instance = null;
        $cfg->cfg = null;
    }
}
